package com.bdqn.ch02.SL;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * CollectMessageAdd
 * 示例 4 添加手机收藏信息
 * @aurhor Administrator  whs
 * @since 2024/6/27
 */
public class CollectMessageAdd {

    public static void main(String[] args) {
        //1. 得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            // 2. 从 DOM 工厂获得 DOM 解析器
            DocumentBuilder db = dbf.newDocumentBuilder();

            // 3. 解析XML文档 得到一个 Document 即DOM 树
            Document doc = db.parse("D:\\Frame\\frames\\web\\collectMessage.xml");

             // 4. 首先 创建Brand 节点
            Element brandElement = doc.createElement("Brand");
            brandElement.setAttribute("name","三星");

            // 5.  然后 创建 Type 节点
            Element typeElement = doc.createElement("Type");
            typeElement.setAttribute("name","NoteX");

            // 6.  最后 添加子父关系
            brandElement.appendChild(typeElement);
            Element phoneElement = (Element)doc.getElementsByTagName("phoneInfo").item(0);
            phoneElement.appendChild(brandElement);

            // 7.保存 XML 文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);

            // 8.设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result = new StreamResult(new FileOutputStream("D:\\Frame\\frames\\web\\collectMessage.xml"));

            // 9. 把 DOM 树转换为 XML 文件
            transformer.transform(domSource,result);

        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }
}
